// 后台脚本，负责处理扩展的核心功能

// 当扩展安装或更新时初始化
chrome.runtime.onInstalled.addListener(() => {
  // 创建右键菜单
  chrome.contextMenus.create({
    id: 'downloadAllResources',
    title: '下载所有资源',
    contexts: ['browser_action']
  });

  chrome.contextMenus.create({
    id: 'downloadImages',
    title: '下载所有图片',
    contexts: ['browser_action']
  });

  chrome.contextMenus.create({
    id: 'downloadVideos',
    title: '下载所有视频',
    contexts: ['browser_action']
  });

  chrome.contextMenus.create({
    id: 'downloadAudios',
    title: '下载所有音频',
    contexts: ['browser_action']
  });

  // 初始化存储
  chrome.storage.local.set({
    panelVisible: false,
    resources: {
      images: [],
      videos: [],
      audios: []
    }
  });
});

// 处理右键菜单点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'downloadAllResources') {
    chrome.tabs.sendMessage(tab.id, { action: 'downloadAll' });
  } else if (info.menuItemId === 'downloadImages') {
    chrome.tabs.sendMessage(tab.id, { action: 'downloadImages' });
  } else if (info.menuItemId === 'downloadVideos') {
    chrome.tabs.sendMessage(tab.id, { action: 'downloadVideos' });
  } else if (info.menuItemId === 'downloadAudios') {
    chrome.tabs.sendMessage(tab.id, { action: 'downloadAudios' });
  }
});

// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'getResources') {
    // 获取资源列表
    chrome.storage.local.get('resources', (data) => {
      sendResponse(data.resources);
    });
    return true; // 异步响应需要返回true
  } else if (request.action === 'updateResources') {
    // 更新资源列表
    chrome.storage.local.set({ resources: request.resources });
  } else if (request.action === 'togglePanel') {
    // 切换面板可见性
    chrome.storage.local.get('panelVisible', (data) => {
      const newState = !data.panelVisible;
      chrome.storage.local.set({ panelVisible: newState });
      sendResponse({ panelVisible: newState });
    });
    return true; // 异步响应需要返回true
  } else if (request.action === 'downloadResource') {
    // 下载单个资源
    chrome.downloads.download({
      url: request.url,
      filename: request.filename,
      saveAs: false
    });
  }
});